<?php

namespace app\common\business;

use app\common\lib\Arr;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class AdminRole {

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\AdminRole();
    }

    /**
     * 获取分页列表
     * @throws Exception
     */
    public function getTableList($page=null,$limit=null,$roleName='',$status=null): array
    {
        $where=[
            ['role_name','like','%'.$roleName.'%']
        ];
        if($status===0||!empty($status)){
            $where[]=['status','=',$status];
        }
        return $this->model->getTableList($where,$page,$limit);
    }

    /**
     * 根据ID查询权限树
     * @throws Exception
     */
    public function getRoleTreeById($id): array
    {
        $allTree=(new \app\common\model\mysql\AdminPermission())->getAllTree();
        $mineRule=empty($id)?[]:self::getRuleById($id);
        return Arr::getTree($allTree,'pid','childList','perms',$mineRule);
    }

    /**
     * 根据id获取
     * @param $id
     * @return false|string[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getRuleById($id){
        $data=$this->model->getRuleById($id);
        return explode(';',$data['rules']);
    }

    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            unset($data['id']);
        }
        if(isset($data['rules'])){
            $data['rules']=str_replace(',',';',$data['rules']);
        }
        return $this->model->saveData($data);
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        return $this->model->deleteById($id);
    }

    /**
     * 根据id修改状态
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function updateStatus($data){
        if(empty($data['id'])){
            throw new Exception('参数错误');
        }
        return $this->model->updateStatus($data);
    }

    /**
     * 是否超级管理员
     * @param $role
     * @return bool
     */
    public function isRoleAdmin($role){
        $flag = false;

        in_array($role,config('role.admin')) && $flag = true;
        return $flag;
    }

    /**
     * 是否各县市
     * @param $role
     * @return bool
     */
    public function isRoleArea($role){
        $flag = false;

        in_array($role,config('role.area')) && $flag = true;
        return $flag;
    }
}
